package initPkg

import (
	"fmt"

	"github.com/hashicorp/consul/api"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	//少引入了一个包
	_ "github.com/mbobakov/grpc-consul-resolver" // It's important

	"2106a-zg5/work/day15/user_api/global"
	"2106a-zg5/work/day15/user_srv/initPkg"
	"2106a-zg5/work/day15/user_srv/proto"
)

func DialSrvInit() {
	//实例化consul实例
	cfg := api.DefaultConfig()
	//go语言连接 consul 地址
	cfg.Address = "127.0.0.1:8500"
	//生成一个 客户端
	consulClient, _ := api.NewClient(cfg)
	//通过 方法 去访问路由
	filter, err := consulClient.Agent().ServicesWithFilter("Service == user_srv")
	if err != nil {
		fmt.Println(err)
		return
	}
	var address string
	var port int
	for _, v := range filter {
		address = v.Address
		port = v.Port
	}
	initPkg.LoggerInit()
	zap.S().Debug(address)
	zap.S().Debug(port)
	dial, err := grpc.Dial(fmt.Sprintf("%s:%d", address, port), grpc.WithInsecure())
	if err != nil {
		zap.S().Info(err)
		return
	}
	//延迟 释放内存
	//defer dial.Close()
	//创建客户端
	global.UserService = proto.NewUserServiceClient(dial)
}

func SrvInit() {
	initPkg.LoggerInit()
	//name := global.SrvConfigInfo.Consul.Name
	//host := global.SrvConfigInfo.Consul.Host
	//port := global.SrvConfigInfo.Consul.Port
	//zap.S().Info(name, host, port)
	//我们通过consul得到callID
	conn, err := grpc.Dial(
		fmt.Sprintf("consul://%s:%d/%s?wait=14s", global.UserConfigInfo.Consul.Host, global.UserConfigInfo.Consul.Port, global.UserConfigInfo.Consul.Name),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		//通过负载均衡的策略返回callID
		//loadBalancingPolicy 负载均衡侧罗
		//round_robin 轮询策略
		//ring_hash 一致性hash
		//random 随机
		//least_request 最小请求数
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
	)
	if err != nil {
		zap.S().Panic(err.Error())
	}
	fmt.Println(conn)
	global.UserService = proto.NewUserServiceClient(conn)
}
